<template>
    <div id="course">
        <!-- 线索表单 -->
        <el-form v-show="formFlag" :model="params" :inline="true" label-width="80" class="demo-form-inline">
            <el-form-item label="客户姓名">
                <el-input v-model="params.name" placeholder="请输入客户姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="客户手机">
                <el-input v-model="params.phone" placeholder="请输入客户手机号码" clearable></el-input>
            </el-form-item>
            <el-form-item label="归属人">
                <el-input v-model="params.owner" placeholder="请输入线索归属人" clearable></el-input>
            </el-form-item>
            <el-form-item label="渠道来源">
                <el-select v-model="params.channelId" placeholder="渠道来源" clearable>
                    <el-option v-for="(item, index) in channelList" :key="item.channelId" :value="item.channelId"
                        :label="item.channelName" />
                </el-select>
            </el-form-item>
            <el-form-item label="线索状态">
                <el-select v-model="params.status" placeholder="线索状态" clearable>
                    <el-option v-for="(item, index) in statusList" :key="item.dictValue" :value="item.dictValue"
                        :label="item.dictLabel" />
                </el-select>
            </el-form-item>
            <el-form-item label="跟进时间">
                <el-date-picker type="daterange" unlink-panels range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期" prefix-icon="PieChart" v-model="timeValue" clearable style="width: 400px;" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getClueList()"><el-icon class="form-icon">
                        <Search />
                    </el-icon>搜索</el-button>
                <el-button @click="resetFn"><el-icon class="form-icon">
                        <Refresh />
                    </el-icon>重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作栏按钮 -->
        <ActionBar v-model:titFlag="titFlag" v-model:dialogFlag="dialogFlag" v-model:formFlag="formFlag"
            v-model:btnFlagArr="btnFlagArr" @delFn="handleDelFn" @touchDerive="deriveXlsx" @editPrepare="editPrepare"
            :getList="getClueList">
        </ActionBar>

        <!-- 表格 -->
        <el-table v-loading="loadingFlag" :data="clueList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="clueId" label="线索编号" width="80" align="center" show-overflow-tooltip />
            <el-table-column prop="name" label="客户姓名" width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="phone" label="手机号码" width="120" align="center" show-overflow-tooltip />
            <el-table-column prop="channelName" label="渠道来源" width="120" align="center" />
            <el-table-column prop="createTime" label="创建时间" width="180" align="center">
                <template #default="scope">
                    {{ scope.row.createTime.replace('T', ' ') }}
                </template>
            </el-table-column>
            <el-table-column prop="createBy" label="线索归属" width="120" align="center" />
            <el-table-column prop="status" label="线索状态" width="150" align="center">
                <template #default="scope">
                    <el-tag v-if="scope.row.status === 1">已分配</el-tag>
                    <el-tag type="success" v-else-if="scope.row.status === 2">跟进中</el-tag>
                    <el-tag v-else-if="scope.row.status === 3">回收</el-tag>
                    <el-tag v-else-if="scope.row.status === 4">伪线索</el-tag>
                    <el-tag type="danger" v-else>未知</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="nextTime" label="下次跟进时间" width="180" align="center">
                <template #default="scope">
                    {{ scope.row.nextTime.replace('T', ' ') }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" text :icon="View">查看</el-button>
                    <el-button type="primary" text :icon="Pointer" v-if="scope.row.status !== 0" @click="distributeFn(scope.row.clueId)">分配</el-button>
                    <el-button type="primary" text :icon="TopRight" v-if="scope.row.createBy == 'admin' && scope.row.status !== 0">跟进</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 页码 -->
        <Pagination v-model:total="total" v-model:list="params" @getList="getClueList"></Pagination>

        <!-- 新增 && 删除  弹窗 -->
        <Dialog ref="dialogRef" v-model:titFlag="titFlag" v-model:dialogFlag="dialogFlag" :channelList="channelList"
            :activityList="activityList" @dialogList="addClue"></Dialog>

        <!-- 分配弹窗 -->
        <DistributeDialog></DistributeDialog>
    </div>
</template>

<script setup lang="ts">
import ActionBar from '@/components/LCommon/ActionBar'
import Pagination from '@/components/LCommon/Pagination'
import DistributeDialog from './components/DistributeDialog.vue'
import Dialog from './components/Dialog.vue'
import { View, Pointer, TopRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import { apiGetClueList, apiDelClueList, apiDeriveXlsx, apiAddClue, apiChannelList, apiStatusList, apiEditList, apiActivityList, apiEditPrepare } from '@/api/clue/clue'
import { ref, watch } from 'vue'
import dayjs from 'dayjs'
import comhooks from '@/hooks/DeriveXlsx'
import { useClueStore } from '../../../store/modules/clue';
import { storeToRefs } from 'pinia';

const cluePinia = useClueStore()
const { aaa } = storeToRefs(cluePinia)
const { distributeFn } = cluePinia

const myhooks = comhooks()

// 表格加载开关
const loadingFlag = ref(false)

// 获取线索管理数据
const clueList = ref([])
const total: number = ref(0)
const listObj = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    phone: '',
    owner: '',
    status: '',
    params: {
        beginTime: '',
        endTime: ''
    }
}
const params = ref({ ...listObj })
const getClueList = async () => {
    loadingFlag.value = true
    const res = await apiGetClueList(params.value)
    clueList.value = res.rows
    total.value = res.total
    loadingFlag.value = false
}
getClueList()

// 渠道来源数据
const channelList = ref([])
const channelListFn = async () => {
    const res = await apiChannelList()
    channelList.value = res.data
}
channelListFn()

// 获取线索状态
const statusList = ref([])
const statusListFn = async () => {
    const res = await apiStatusList()
    statusList.value = res.data
}
statusListFn()

// 重置
const resetFn = () => {
    params.value = { ...listObj }
    getClueList()
}

// 选择时间范围
const timeValue = ref('')
watch(timeValue, (newValue, oldValue) => {
    if (newValue && newValue.length === 2) {
        params.value.params['beginTime'] = dayjs(newValue[0]).format('YYYY-MM-DD HH:mm:ss')
        params.value.params['endTime'] = dayjs(newValue[1]).format('YYYY-MM-DD HH:mm:ss')
    } else {
        params.value.params['beginTime'] = ''
        params.value.params['endTime'] = ''
    }
})

// 选择表格哪一行
const btnFlagArr = ref([])
const handleSelectionChange = (val) => {
    btnFlagArr.value = val
}

// 删除
const handleDelFn = (data) => {
    const ids = data.map(item => item.clueId).join(',')
    myhooks.delPointOutFn(ids, apiDelClueList, getClueList)
}

// form表单开关
const formFlag = ref(true)

// 导出xlsx
const deriveXlsx = async () => {
    const res = await apiDeriveXlsx(params.value)
    myhooks.deriveXlsx(res)
}

// 定义弹窗开关
const dialogFlag = ref(false)

// 新增 or 修改
const dialogRef = ref<any>(null)
// 活动信息
const activityList = ref([])
// 判断新增或修改
const titFlag = ref('add')
// 修改前的准备
const editPrepare = async () => {
    const res = await apiEditPrepare(btnFlagArr.value[0].clueId)
    const resActivity = await apiActivityList(res.data.channelId)
    activityList.value = resActivity.data
    dialogRef.value.listObj = { ...btnFlagArr.value[0], ...res.data }
    // console.log(dialogRef.value.listObj)
}

// 新增和修改确认函数
const addClue = async (list) => {
    if (titFlag.value === 'add') {
        try {
            await apiAddClue(list.value)
            ElMessage.success('添加成功')
        } catch (err) { }
    } else {
        try {
            await apiEditList({ ...dialogRef.value.listObj })
            ElMessage.success('修改成功')
        } catch (err) { }
    }
    getClueList()
}





// 确认分配后重新刷新页面，
watch(aaa, () => {
    getClueList()
})


</script>

<style lang="scss" scoped>
#course {
    padding: 20px;

    .demo-form-inline {

        .el-input {
            --el-input-width: 212px;
        }

        .el-select {
            --el-select-width: 212px;
        }
    }
}

.form-icon {
    margin-right: 6px;
}
</style>